package com.zwk.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.aliyuncs.vod.model.v20170321.GetVodTemplateRequest;
import com.zwk.base.entity.CommonResult;
import com.zwk.base.handler.GuLiException;
import com.zwk.vod.service.VodService;
import com.zwk.vod.util.InitVodClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;


/**
 * @author zwk
 * @create 2022/8/24 16:31
 */
@RestController
@CrossOrigin
@RequestMapping("/vod")
public class VodController {

    @Autowired
    private VodService vodService;

    @Value("${aliyun.oss.file.keyid}")
    private String keyId;

    @Value("${aliyun.oss.file.keysecret}")
    private String keySecret;

    // 上传视频到阿里云
    @PostMapping("/uploadAliyunVideo")
    public CommonResult uploadAliyunVideo(MultipartFile file){

        String videoId = vodService.uploadAliyun(file);

        return CommonResult.ok().data("videoId", videoId);
    }

    // 删除阿里云中的视频
    @DeleteMapping("/removeAliyunVideo/{id}")
    public CommonResult removeAliyunVideo(@PathVariable("id") String id){
        boolean result = vodService.removeVideo(id);

        if (result){
            return CommonResult.ok();
        }

        throw new GuLiException(20001, "删除视频失败");
    }

    // 批量删除视频
    @DeleteMapping("/deleteBatch")
    public CommonResult deleteBatch(@RequestParam("videoList") List<String> videoList){
        boolean result = vodService.removeMoreVideo(videoList);
        if (result){
            return CommonResult.ok();
        }

        throw new GuLiException(20001, "批量删除视频失败");
    }

    // 根据视频id获取播放凭证
    @GetMapping("getPlayAuth/{id}")
    public CommonResult getPlayAuth(@PathVariable("id") String id){
        try {
            // 创建初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(keyId, keySecret);
            // 创建获取凭证的request对象response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            // 向request中设置视频id
            request.setVideoId(id);
            //调用方法得到凭证
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth();
            return CommonResult.ok().data("playAuth", playAuth);
        } catch (Exception e){
            e.printStackTrace();
            throw new GuLiException(20001, "获取播放凭证失败");
        }
    }

}
